#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
/*
 * Copyright © 2014, Finium Sdn Bhd, All Rights Reserved
 * 
 * UrlUtil.java
 * Modification History
 * *************************************************************
 * Date             Author                      Comment
 * Jan 3, 2014      Venkaiah Chowdary Koneru    Created
 * *************************************************************
 */
package ${package}.commons.support;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

import ${package}.AppConstants;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Class to contain URL Utility classes
 * 
 * @author Venkaiah Chowdary Koneru
 */
public final class UrlUtil
{
    private static final Log LOG = LogFactory.getLog(UrlUtil.class);
    private static final int HTTP_OK_STATUS_CODE = 200;

    /**
     * Constructor. Private to prevent unnecessary instantiation.
     */
    private UrlUtil()
    {
    }

    /**
     * Encodes <code>url</code> to UTF-8
     * 
     * @param url
     *            URL string to encode to UTF-8
     * @return encoded URL string
     */
    public static String encodeURL(String url)
    {
        try
        {
            return URLEncoder.encode(url, AppConstants.UTF8);
        }
        catch (UnsupportedEncodingException e)
        {
            LOG.error("Exception while encoding", e);

            return null;
        }
    }

    /**
     * Decodes the <code>url</code> from UTF-8 encoded characters.
     * 
     * @param url
     *            URL string to decode from UTF-8
     * @return decoded URL string
     */
    public static String decodeURL(String url)
    {
        try
        {
            return URLDecoder.decode(url, AppConstants.UTF8);
        }
        catch (UnsupportedEncodingException e)
        {
            LOG.error("Exception while decoding", e);
            return null;
        }
    }

    /**
     * Determine whether there is a URL address
     * 
     * @param url
     * @return <code>true</code> if <code>url</code> responds HTTP 200 otherwise
     *         returns <code>false</code>
     */
    public static boolean isURLExist(String url)
    {
        try
        {
            URL u = new URL(url);
            HttpURLConnection urlconn = (HttpURLConnection) u.openConnection();
            int state = urlconn.getResponseCode();

            return (state == HTTP_OK_STATUS_CODE);
        }
        catch (IOException e)
        {
            LOG.error("Exception while checking URL", e);
            return false;
        }
    }
}
